package com.heima.wemedia.interceptor;

import cn.hutool.core.util.StrUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class WmTokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取请求头的token
        String token = request.getHeader("token");

        // 2. 判断token是否为空
        if (StrUtil.isBlank(token)) {
            throw new Exception("token不能为空");
        }

        // 3. 判断token是否有效
        boolean verify = JWTUtil.verify(token, "wemedia".getBytes());
        if (!verify) {
            throw new Exception("token已失效");
        }

        // 4. 从token中获取用户id
        JWT jwt = JWTUtil.parseToken(token);
        // 获取载荷里面的某个字段
        Object id = jwt.getPayload("id");

        // 5. 将用户id写入ThreadLocal WmThreadLocalUtil
        WmUser wmUser = new WmUser();
        wmUser.setId((Integer) id);
        WmThreadLocalUtil.setUser(wmUser);

        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 6. 清除ThreadLocal
        WmThreadLocalUtil.clear();
    }
}